'use client';

import React, { useState } from 'react';
import { Layout } from '@/components/layout';
import { useApp } from '@/hooks';
import { profileQuestions, validateAnswer, getQuestionProgress } from '@/data/questions';
import { Question, UserProfile, TechRole, TechPreference, ExperienceLevel, AttendancePurpose, TimePreference } from '@/types';
import { useRouter } from 'next/navigation';

const ProfilePage: React.FC = () => {
  const { setUserProfile } = useApp();
  const router = useRouter();
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [answers, setAnswers] = useState<Record<string, string | string[]>>({});
  const [errors, setErrors] = useState<Record<string, string>>({});

  const currentQuestion = profileQuestions[currentQuestionIndex];
  const progress = getQuestionProgress(answers);
  const isLastQuestion = currentQuestionIndex === profileQuestions.length - 1;

  // 处理答案变更
  const handleAnswerChange = (questionId: string, value: string | string[]) => {
    const newAnswers = { ...answers, [questionId]: value };
    setAnswers(newAnswers);
    
    // 清除当前问题的错误
    if (errors[questionId]) {
      const newErrors = { ...errors };
      delete newErrors[questionId];
      setErrors(newErrors);
    }
  };

  // 验证当前问题
  const validateCurrentQuestion = (): boolean => {
    const answer = answers[currentQuestion.id];
    const isValid = validateAnswer(currentQuestion, answer);
    
    if (!isValid) {
      setErrors({
        ...errors,
        [currentQuestion.id]: '请完成此必填项'
      });
    }
    
    return isValid;
  };

  // 下一题
  const handleNext = () => {
    if (validateCurrentQuestion()) {
      if (isLastQuestion) {
        handleSubmit();
      } else {
        setCurrentQuestionIndex(prev => prev + 1);
      }
    }
  };

  // 上一题
  const handlePrevious = () => {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex(prev => prev - 1);
    }
  };

  // 提交画像
  const handleSubmit = () => {
    // 验证所有答案
    let isValid = true;
    const newErrors: Record<string, string> = {};

    for (const question of profileQuestions) {
      const answer = answers[question.id];
      if (!validateAnswer(question, answer)) {
        newErrors[question.id] = '请完成此必填项';
        isValid = false;
      }
    }

    if (!isValid) {
      setErrors(newErrors);
      return;
    }

    // 构建用户画像
    const profile: UserProfile = {
      id: `profile-${Date.now()}`,
      role: answers.q1 as TechRole,
      techPreferences: answers.q2 as TechPreference[],
      experienceLevel: answers.q3 as ExperienceLevel,
      attendancePurpose: answers.q4 as AttendancePurpose[],
      timePreferences: answers.q5 as TimePreference[],
      createdAt: new Date(),
      updatedAt: new Date()
    };

    setUserProfile(profile);
    router.push('/recommendations');
  };

  // 渲染选择选项
  const renderOptions = (question: Question) => {
    const currentAnswer = answers[question.id];

    if (question.type === 'single_choice') {
      return (
        <div className="space-y-4">
          {question.options?.map((option) => (
            <label
              key={option.id}
              className={`
                flex items-center p-6 rounded-lg border-2 cursor-pointer transition-all duration-200 w-full min-h-[80px]
                ${currentAnswer === option.value 
                  ? 'border-primary bg-primary/10 text-primary shadow-md' 
                  : 'border-border hover:border-primary/50 hover:bg-hover hover:shadow-sm'
                }
              `}
            >
              <input
                type="radio"
                name={question.id}
                value={option.value}
                checked={currentAnswer === option.value}
                onChange={(e) => handleAnswerChange(question.id, e.target.value)}
                className="sr-only"
              />
              <div className="flex-1 pr-4">
                <div className="font-semibold text-lg">{option.label}</div>
                {option.description && (
                  <div className="text-sm text-muted mt-2 leading-relaxed">{option.description}</div>
                )}
              </div>
              <div className={`
                w-5 h-5 rounded-full border-2 flex items-center justify-center
                ${currentAnswer === option.value 
                  ? 'border-primary bg-primary' 
                  : 'border-border'
                }
              `}>
                {currentAnswer === option.value && (
                  <div className="w-2 h-2 rounded-full bg-white"></div>
                )}
              </div>
            </label>
          ))}
        </div>
      );
    }

    if (question.type === 'multiple_choice') {
      const selectedValues = (currentAnswer as string[]) || [];
      const maxSelections = question.id === 'q2' ? 5 : undefined;

      return (
        <div className="space-y-4">
          {maxSelections && (
            <div className="text-sm text-muted mb-4">
              已选择 {selectedValues.length}/{maxSelections} 项
            </div>
          )}
          {question.options?.map((option) => {
            const isSelected = selectedValues.includes(option.value);
            const isDisabled = maxSelections && !isSelected && selectedValues.length >= maxSelections;

            return (
              <label
                key={option.id}
                className={`
                  flex items-center p-6 rounded-lg border-2 cursor-pointer transition-all duration-200 w-full min-h-[80px]
                  ${isSelected 
                    ? 'border-primary bg-primary/10 text-primary shadow-md' 
                    : isDisabled
                    ? 'border-border bg-gray-50 text-muted cursor-not-allowed opacity-60'
                    : 'border-border hover:border-primary/50 hover:bg-hover hover:shadow-sm'
                  }
                `}
              >
                <input
                  type="checkbox"
                  value={option.value}
                  checked={isSelected}
                  disabled={isDisabled}
                  onChange={(e) => {
                    let newValues: string[];
                    
                    // 特殊处理时间偏好问题的逻辑
                    if (question.id === 'q5') {
                      if (e.target.checked) {
                        if (option.value === 'full_day') {
                          // 选择全天候时，清除其他所有选项
                          newValues = ['full_day'];
                        } else {
                          // 选择具体时间段时，先移除全天候选项，再添加当前选项
                          newValues = selectedValues.filter(v => v !== 'full_day');
                          newValues = [...newValues, option.value];
                        }
                      } else {
                        // 取消选择
                        newValues = selectedValues.filter(v => v !== option.value);
                      }
                    } else {
                      // 其他问题保持原有逻辑
                      newValues = e.target.checked
                        ? [...selectedValues, option.value]
                        : selectedValues.filter(v => v !== option.value);
                    }
                    
                    handleAnswerChange(question.id, newValues);
                  }}
                  className="sr-only"
                />
                <div className="flex-1 pr-4">
                  <div className="font-semibold text-lg">{option.label}</div>
                  {option.description && (
                    <div className="text-sm text-muted mt-2 leading-relaxed">{option.description}</div>
                  )}
                </div>
                <div className={`
                  w-5 h-5 rounded border-2 flex items-center justify-center
                  ${isSelected 
                    ? 'border-primary bg-primary' 
                    : 'border-border'
                  }
                `}>
                  {isSelected && (
                    <svg className="w-3 h-3 text-white" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                    </svg>
                  )}
                </div>
              </label>
            );
          })}
        </div>
      );
    }

    return null;
  };

  return (
    <Layout>
      <div className="container mx-auto px-4 py-8">
        <div className="max-w-4xl mx-auto">
          {/* 进度条 */}
          <div className="mb-8">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm font-medium text-foreground">构建用户画像</span>
              <span className="text-sm text-muted">{progress}%</span>
            </div>
            <div className="w-full bg-border rounded-full h-2">
              <div 
                className="bg-gradient-primary h-2 rounded-full transition-all duration-300"
                style={{ width: `${progress}%` }}
              ></div>
            </div>
            <div className="flex justify-between text-xs text-muted mt-2">
              <span>第 {currentQuestionIndex + 1} 题</span>
              <span>共 {profileQuestions.length} 题</span>
            </div>
          </div>

          {/* 问题卡片 */}
          <div className="card mb-8 p-8">
            <div className="mb-8">
              <h2 className="text-2xl font-bold text-foreground mb-4">
                {currentQuestion.title}
              </h2>
              {currentQuestion.description && (
                <p className="text-muted text-lg leading-relaxed">{currentQuestion.description}</p>
              )}
            </div>

            {renderOptions(currentQuestion)}

            {errors[currentQuestion.id] && (
              <div className="mt-4 p-3 bg-error/10 border border-error/20 rounded-lg">
                <p className="text-error text-sm">{errors[currentQuestion.id]}</p>
              </div>
            )}
          </div>

          {/* 导航按钮 */}
          <div className="flex justify-between">
            <button
              onClick={handlePrevious}
              disabled={currentQuestionIndex === 0}
              className="btn btn-secondary px-6 py-3 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              上一题
            </button>

            <button
              onClick={handleNext}
              className="btn btn-primary px-6 py-3"
            >
              {isLastQuestion ? '完成画像构建' : '下一题'}
            </button>
          </div>

          {/* 问题导航器 */}
          <div className="mt-8 flex justify-center">
            <div className="flex space-x-2">
              {profileQuestions.map((_, index) => (
                <button
                  key={index}
                  onClick={() => setCurrentQuestionIndex(index)}
                  className={`
                    w-8 h-8 rounded-full text-xs font-medium transition-all duration-200
                    ${index === currentQuestionIndex
                      ? 'bg-primary text-white shadow-md'
                      : answers[profileQuestions[index].id]
                      ? 'bg-success text-white'
                      : 'bg-border text-muted hover:bg-hover'
                    }
                  `}
                >
                  {index + 1}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </Layout>
  );
};

export default ProfilePage;